<script setup lang="ts">
import { onServerPrefetch, useSSRContext, watch, onBeforeMount, computed } from 'vue';
import { useRoute } from 'vue-router';
import { useTitleForClient } from '@/home/hooks/browser';

export interface ItemType {
  path: string,
  label: string
}

const props = defineProps({
  itemList: {
    type: Array<ItemType>,
    default: () => [],
  },
});

const route = useRoute();
const { setTitle } = useTitleForClient();

// 在路由变化时更新 selectedIndex
const selectedIndex = computed(() => props.itemList.findIndex((item) => route.path.indexOf(item.path) === 0));

const getTitle = () => props.itemList[selectedIndex.value]?.label;

onBeforeMount(() => {
  setTitle(getTitle());
});

onServerPrefetch(async () => {
  const ctx = useSSRContext() as Record<string, any>;
  ctx.title = getTitle();
});

watch(() => route.path, () => {
  setTitle(getTitle());
});
</script>

<template>
  <section class="component-router-tabs border-t-1">
    <section class="h-64 flex-center bg-hex-fff shadow-[0px_1px_6px_0px_rgba(0,0,0,0.06)]">
      <div class="flex-x-center">
        <div v-for="(item, index) in props.itemList" :key="item.path" class="ml-40 border-l-1 border-hex-F2F5F7 pl-40 first:(ml-0 border-l-0 pl-0)">
          <RouterLink
            class="block px-16 text-14 no-underline focus-visible:outline-unset"
            :class="[selectedIndex === index ? 'text-[#345de2] font-500' : 'text-[#292929] font-400']"
            :to="item.path"
          >
            {{ item.label }}
          </RouterLink>
        </div>
      </div>
    </section>

    <RouterView />
  </section>
</template>
